package com.lengyu.vxminiprogram.common;

import com.alibaba.excel.EasyExcel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class ReadExcelUtil<T> {
    private Logger logger = LoggerFactory.getLogger(ReadExcelUtil.class);
    public List<T> readExcel(MultipartFile file,
                                             Class clazz) {
        try{
            return readExcel(0,3,file,clazz);
        }
        catch (Exception ex){
            logger.error("Excel读取失败",ex);
            return null;
        }

    }


    /**
     * sheetNo 读取excel中哪个sheet页
     * headLineMun sheet页第几行开始读取
     */
    public List<T> readExcel(int sheetNo,
                                             int headLineMun,
                                             MultipartFile file,
                                             Class clazz) {
        try{
            if (null == file) return null;
            List<T> list = EasyExcel.read(file.getInputStream(),clazz,null).headRowNumber(headLineMun).sheet(sheetNo).doReadSync();
            return list;
        }
        catch (Exception ex){
            logger.error("Excel读取失败",ex);
            return null;
        }

    }

    /**
     * sheetNo 读取excel中哪个sheet页
     * headLineMun sheet页第几行开始读取
     */
    public List<T> readExcel(int sheetNo,
                             int headLineMun,
                             String fileName,
                             Class clazz) {
        try{
            if (StringUtils.isBlank(fileName)) return null;
            List<T> list = EasyExcel.read(fileName,clazz,null).headRowNumber(headLineMun).sheet(sheetNo).doReadSync();
            return list;
        }
        catch (Exception ex){
            logger.error("Excel读取失败",ex);
            return null;
        }

    }


    public File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    public void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
